﻿using Microsoft.AspNetCore.Http;
using NETCore.Auth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;

namespace NETCore.Auth.Extensions
{
	public static class CookieSessionHelper
	{
		public static void SetCookies(this HttpContext httpContext, string key, string value, int minute = 30)
		{
			httpContext.Response.Cookies.Append(key, value, new CookieOptions
			{
				Expires = DateTime.Now.AddMinutes(minute)
			});
		}

		public static void DeleteCookies(this HttpContext httpContext, string key)
			=> httpContext.Response.Cookies.Delete(key);

		public static string GetCookiesValue(this HttpContext httpContext, string key)
		{
			httpContext.Request.Cookies.TryGetValue(key, out string value);
			return value;
		}


		public static CurrentUser GetCurrentByCookie(this HttpContext httpContext)
		{
			
			httpContext.Request.Cookies.TryGetValue("CurrentUser", out string sUser);
			if (sUser == null)
			{
				return null;
			}
			else
			{
				//CurrentUser currentUser = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(sUser);
				CurrentUser currentUser = JsonSerializer.Deserialize<CurrentUser>(sUser);
				return currentUser;
			}
		}
	}
}
